package cn.bird.storm.validated.paramcheck;

import cn.bird.exception.BusiException;
import cn.bird.storm.validated.paramcheck.inter.ICheckBean;
import cn.bird.storm.validated.paramcheck.inter.ICheckModel;
import cn.bird.storm.validated.paramcheck.tool.CheckNode;
import cn.bird.util.CommonFunUtil;
import cn.hutool.core.util.ObjectUtil;

import java.util.Map;
import java.util.function.Supplier;


public class RichUtil {
    /**
     * @param key                  校验模式的名称
     * @param iCheckBean           检验组装bean
     * @param defaultModelSupplier 当ParamCheckComponent.getCheckNode().getModelMap()中没有的{@link ICheckModel} 需要赋默认值
     */
    @SuppressWarnings("unchecked")
    protected static <T> ParameterCheckBuilder richCheckModelMap(String key, ICheckBean<T> iCheckBean, Supplier<ICheckModel<T>> defaultModelSupplier) {
        CheckNode checkNode = ParamCheckComponent.getCheckNode();
        if (ObjectUtil.isNull(checkNode)
                || ObjectUtil.isNull(checkNode.getParameterCheckBuilder())
                || ObjectUtil.isNull(checkNode.getModelMap())) {
            throw new BusiException("参数检验未知错误！");
        }
        Map<String, ICheckModel> checkModelMap = checkNode.getModelMap();
        if (ObjectUtil.hasEmpty(key, iCheckBean, defaultModelSupplier)) {
            return checkNode.getParameterCheckBuilder();
        }
        //每个key拿出的一定是自己的ICheckModel泛型
        ICheckModel<T> checkModel = checkModelMap.getOrDefault(key, defaultModelSupplier.get());
        richCheckModel(checkModel, iCheckBean);

        checkModelMap.put(key, checkModel);
        return checkNode.getParameterCheckBuilder();
    }

    /**
     * 统一处理添加checkBean的逻辑
     */
    protected static <T> void richCheckModel(ICheckModel<T> checkModel, ICheckBean<T> tiCheckBean) {
        checkModel.setCheckBeans(CommonFunUtil.addToList(checkModel.getCheckBeans(), tiCheckBean));
    }

}
